<template>
  <el-select
    v-model="category"
    filterable
    :popper-append-to-body="false"
    :teleported="false"
    @change="changeData"
    placeholder="品类"
    clearable
  >
    <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
  </el-select>
</template>

<script setup lang="ts">
import categoryApi from '../../api/categoryApi.js';
import materialApi from '../../api/materialApi.js';
import { ref, reactive, onMounted, toRefs } from 'vue';

const props = defineProps({
  type: {
    type: String,
    default: ''
  }
});
const emit = defineEmits(['change']);
const state = reactive({
  categoryList: [],
  category: ''
});

// const { type } = toRefs(props);
const { categoryList, category } = toRefs(state);
onMounted(() => {
  loadcategoryList();
});
function loadcategoryList() {
  if (props.type) {
    categoryApi.getcategoryType({ 'type': props.type }).then((res) => {
      res.data.push({ 'id': '', 'name': '全部分类' });
      if (res.data && res.data.length > 0) {
        state.categoryList = res.data;
      }
    });
  } else {
    materialApi.getCategory(null).then((res) => {
      res.data.push({ 'id': '', 'name': '全部分类' });
      if (res.data && res.data.length > 0) {
        state.categoryList = res.data;
      }
    });
  }
}
function changeData(value) {
  emit('change', value);
}
function reset() {
  state.category = '';
}

defineExpose({
  state,
  reset
});
</script>

<style></style>
